package com.star.oauth.service.impl;

import com.star.oauth.service.ClientService;
import com.star.oauth.service.OAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * OAuth相关处理：authCode 添加/移除  accessToken的添加/移除 。。。。。
 * */
@Service
public class OAuthServiceImpl implements OAuthService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    ClientService clientService;


    @Override
    public void addAuthCode(String authCode, String username) {
        redisTemplate.opsForValue().set(authCode,username);
    }

    @Override
    public String removeAuthCode(String authCode) {
 
        String s = redisTemplate.opsForValue().get(authCode);
        redisTemplate.delete(authCode);
        return s ;
    }

    @Override
    public void addAccessToken(String accessToken, String username) {
        redisTemplate.opsForValue().set(accessToken,username,3600, TimeUnit.SECONDS);
    }

    @Override
    public void addRefreshToken(String refreshToken, String username) {
        redisTemplate.opsForValue().set(refreshToken,username,7200, TimeUnit.SECONDS);
    }

    @Override
    public boolean checkAuthCode(String authCode) {
        return Objects.nonNull(redisTemplate.opsForValue().get(authCode));
    }

    @Override
    public boolean checkAccessToken(String accessToken) {
        return Objects.nonNull(redisTemplate.opsForValue().get(accessToken));
    }

    @Override
    public boolean checkRefreshToken(String accessToken) {
        return false;
    }

    @Override
    public String getUsernameByAuthCode(String authCode) {
        return redisTemplate.opsForValue().get(authCode);
    }

    @Override
    public String getUsernameByAccessToken(String accessToken) {
        return redisTemplate.opsForValue().get(accessToken);
    }

    @Override
    public String getUsernameByRefresh(String refreshToken) {

        return redisTemplate.opsForValue().get(refreshToken);
    }

    @Override
    public long getAccessTokenExpireIn() {
        return 3600L;
    }

    @Override
    public long getRefreshTokenExpireIn() {
        return 7200L;
    }


    @Override
    public boolean checkClientId(String clientId) {
        return Objects.nonNull(clientService.findByClientId(clientId));
    }

    @Override
    public boolean checkClientSecret(String clientSecret) {
        return Objects.nonNull(clientService.findByClientSecret(clientSecret));
    }
}
